package com.hewep.web;

import java.util.List;

import org.sqlite.SQLiteDataSource;

import com.hewep.kit.CacheKit;
import com.hewep.kit.ConfigKit;
import com.hewep.web.controller.IndexController;
import com.hewep.web.controller.ListController;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.core.JFinal;
import com.jfinal.ext.handler.ContextPathHandler;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.dialect.Sqlite3Dialect;
import com.jfinal.plugin.c3p0.C3p0Plugin;
import com.jfinal.render.ViewType;

public class AppConfig extends JFinalConfig{
	@Override
	public void configConstant(Constants me) {
		me.setDevMode(ConfigKit.getBoolean("dev_mode", false));			
		me.setViewType(ViewType.FREE_MARKER);
		me.setFreeMarkerViewExtension(".html");
		me.setBaseViewPath("/WEB-INF/view/");
	}
	
	@Override
	public void configRoute(Routes me) {
		me.add("/", IndexController.class);
		me.add("list", ListController.class);
	}

	@Override
	public void configHandler(Handlers me) {
		//me.add(new UrlSkipHandler("/", false));
		me.add(new ContextPathHandler("ctx_path"));
	}

	@Override
	public void configInterceptor(Interceptors me) {
		//me.add(new TxByRegex(".*(add|del|edit).*"));
	}

	@Override
	public void configPlugin(Plugins me) {			
		String dbPath = PathKit.getWebRootPath()+"/data/tool.db";
		String dbUrl = "jdbc:sqlite:"+dbPath;
		SQLiteDataSource ds = new SQLiteDataSource();
		ds.setUrl(dbUrl);
		ActiveRecordPlugin arp = new ActiveRecordPlugin(ds);
		arp.setDialect(new Sqlite3Dialect());
		arp.setShowSql(true);
		me.add(arp);
	}
	
	@Override
	public void afterJFinalStart() {
		List<Record> records = Db.find("select * from config");
		for (Record record : records) {
			String tableName = record.getStr("item");
			String columns = record.getStr("value");
			String columnRemark = record.getStr("key_value");
			String remarkColumn = record.getStr("value_key");
			CacheKit.cacheByTableName(tableName, CacheKit.COLUMN_REMARK, columnRemark);
			CacheKit.cacheByTableName(tableName, CacheKit.REMARK_COLUMN, remarkColumn);
			CacheKit.cacheByTableName(tableName, CacheKit.COLUMNS, columns);
		}
		super.afterJFinalStart();
	}
	@Override
	public void beforeJFinalStop() {
		
		super.beforeJFinalStop();
	}

	public static void main(String[] args) {
		JFinal.start("WebRoot", 82, "/", 5);
	}
}
